package io.plugin.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.jfinal.plugin.activerecord.Page;
import io.plugin.common.entity.Filter;
import io.plugin.common.entity.Order;
import io.plugin.common.utils.PageUtils;
import io.plugin.common.utils.Query;
import io.plugin.dao.PlanLogDao;
import io.plugin.entity.EchartPlan;
import io.plugin.entity.SSCResultItem;
import io.plugin.enums.GeneralEnum;
import io.plugin.enums.PlanEchartDateEnum;
import io.plugin.enums.PlanTypeEnum;
import io.plugin.model.PlanLog;
import io.plugin.service.SysPlanLogService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SysPlanLogServiceImpl extends BaseServiceImpl<PlanLogDao, PlanLog> implements SysPlanLogService {

  @Autowired
  private RestTemplate normalRestTemplate;

  @Autowired
  private SysPlanLogService sysPlanLogService;

  @Override
  public boolean updatePlan(Integer type) {
    ResponseEntity<String> response = normalRestTemplate.getForEntity("http://gf.20944.com/plan.aspx?type="+type, String.class);
    String body = response.getBody();
    String[] itemArr = body.split("<br />");
    List<SSCResultItem> sscResultItemList = new ArrayList<SSCResultItem>();

    List<Filter> filterList = new ArrayList<>();
    Filter filter = new Filter();
    filter.setProperty("type");
    filter.setOperator(Filter.Operator.eq);
    filter.setValue(type);
    filterList.add(filter);

    filter = new Filter();
    filter.setProperty("create_date");
    filter.setOperator(Filter.Operator.lt);
    filter.setValue(DateUtil.endOfDay(new Date()));
    filterList.add(filter);

    filter = new Filter();
    filter.setProperty("create_date");
    filter.setOperator(Filter.Operator.gt);
    filter.setValue(DateUtil.beginOfDay(new Date()));
    filterList.add(filter);

    Order order = new Order();
    order.setProperty("create_date");
    order.setDirection(Order.Direction.desc);

    Page<PlanLog> planLogPage = this.paginate(1, 1, filterList, order);
    PlanLog lastPlanLog = null;

    if (planLogPage.getList() != null && planLogPage.getList().size() > 0) {
        lastPlanLog = planLogPage.getList().get(0);
    }

    int index = 0;
    for (String item:itemArr) {

      if (item.contains("?") && index != 0) {
        String lastRecord = itemArr[index - 1];
          if(lastPlanLog != null && lastPlanLog.getContent().equals(lastRecord)) {
          return false;
        }
        PlanLog planLog = new PlanLog();
        planLog.setContent(lastRecord);
        if(lastRecord.contains("中")) {
          planLog.setState(1);
        }else {
          planLog.setState(0);
        }
        planLog.setType(type);

        List<Filter> chkFilters = new ArrayList<>();
        Filter chkFilter = new Filter();
        chkFilter.setProperty("create_date");
        chkFilter.setOperator(Filter.Operator.lt);
        chkFilter.setValue(DateUtil.endOfDay(new Date()));
        chkFilters.add(chkFilter);

        chkFilter = new Filter();
        chkFilter.setProperty("create_date");
        chkFilter.setOperator(Filter.Operator.gt);
        chkFilter.setValue(DateUtil.beginOfDay(new Date()));
        chkFilters.add(chkFilter);

        chkFilter = new Filter();
        chkFilter.setProperty("type");
        chkFilter.setOperator(Filter.Operator.eq);
        chkFilter.setValue(type);
        chkFilters.add(chkFilter);


        chkFilter = new Filter();
        chkFilter.setProperty("content");
        chkFilter.setOperator(Filter.Operator.eq);
        chkFilter.setValue(planLog.getContent());
        chkFilters.add(chkFilter);

        List<PlanLog> planLogs = sysPlanLogService.findByFilters(chkFilters);
        if(planLogs != null && planLogs.size() > 0) {
            break;
        }

        planLog.save();
        break;
      }

      index ++;
    }

    return true;
  }

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    Integer type = -1;
    if(params.get("type") != null) {
      type = Integer.parseInt(params.get("type").toString());
    }

    Date searchDate = null;
    if(params.get("planDate") != null && !StringUtils.isBlank(params.get("planDate").toString())) {
//      String planDate = params.get("planDate").toString();
//      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//      try {
//        searchDate = sdf.parse(planDate);
//      } catch (ParseException e) {
//        e.printStackTrace();
//      }
        Long timestamp = Long.parseLong(params.get("planDate").toString());
        searchDate = new Date(timestamp);
    }

    Query<PlanLog> query = new Query<>(params);

    List<Filter> filters = new ArrayList<>();
    if (type != null && type != -1) {
      Filter filter = new Filter();
      filter.setProperty("type");
      filter.setValue(type);
      filter.setOperator(Filter.Operator.eq);
      filters.add(filter);
    }

    if (searchDate != null) {
      Filter filter = new Filter();
      filter.setProperty("create_date");
      Date beginDay = DateUtil.beginOfDay(searchDate);
      filter.setValue(beginDay);
      filter.setOperator(Filter.Operator.gt);
      filters.add(filter);

      filter = new Filter();
      filter.setProperty("create_date");
      Date endDay = DateUtil.endOfDay(searchDate);
      filter.setValue(endDay);
      filter.setOperator(Filter.Operator.lt);
      filters.add(filter);
    }

    Order order = new Order();
    order.setProperty("create_date");
    order.setDirection(Order.Direction.desc);
    Page<PlanLog> pr = this.paginate(query.getCurrPage(), query.getLimit(), filters, order);

    return new PageUtils(pr);
  }

    @Override
    public List<EchartPlan> echart(PlanEchartDateEnum planEchartDateEnum) {
        Date beginOfDay = DateUtil.beginOfDay(new Date());
        int offsetDay = 0;
        switch (planEchartDateEnum) {
            case ONE_WEEK:
                offsetDay = 7;
                break;
            case TOW_WEEK:
                offsetDay = 14;
                break;
            case THREE_WEEK:
                offsetDay = 21;
                break;
            case MONTH:
                offsetDay = 30;
                break;

        }

        List<EchartPlan> echartPlanList = new ArrayList<>();
        for (PlanTypeEnum each: PlanTypeEnum.values()) {
            EchartPlan echartPlan = null;

            for (EchartPlan item:echartPlanList
                 ) {
                if(item.getName().equals(each.getMessage())) {
                    echartPlan = item;
                    break;
                }
            }

            if(echartPlan == null) {
                echartPlan = new EchartPlan();
                echartPlan.setName(each.getMessage());
                echartPlanList.add(echartPlan);
            }

            for (int i = 1; i <= offsetDay; i++) {
                DateTime beginDateTime = DateUtil.offsetDay(beginOfDay, -i);
                Date beginDay = beginDateTime.toJdkDate();
                Date endDay = DateUtil.endOfDay(beginDay);

                List<Filter> filters = new ArrayList<>();

                Filter filter = new Filter();
                filter.setProperty("create_date");
                filter.setValue(beginDay);
                filter.setOperator(Filter.Operator.gt);
                filters.add(filter);

                filter = new Filter();
                filter.setProperty("create_date");
                filter.setValue(endDay);
                filter.setOperator(Filter.Operator.lt);
                filters.add(filter);

                filter = new Filter();
                filter.setProperty("type");
                filter.setValue(each.getCode());
                filter.setOperator(Filter.Operator.eq);
                filters.add(filter);


                Order order = new Order();
                order.setDirection(Order.Direction.asc);
                order.setProperty("create_date");

                Page<PlanLog> planLogPage = sysPlanLogService.paginate(1, 120, filters, order);
                List<PlanLog> planLogList = planLogPage.getList();
                if(planLogList != null && planLogList.size() > 0) {
                    int errorCount = 0;
                    int lastErrorIdx = -1;
                    int continueErrorCount = 0;
                    int idx = 0;
                    for (PlanLog planLog:planLogList
                         ) {
                        idx++;
                        if (planLog.getState() == GeneralEnum.FALSE.getCode()) {
                            if(lastErrorIdx == -1 || lastErrorIdx == (idx -1)) {
                                errorCount++;
                                if(errorCount >= 2) {
                                    errorCount = 0;
                                    lastErrorIdx = -1;
                                    continueErrorCount ++;
                                }
                            }
                        }else {
                            errorCount = 0;
                            lastErrorIdx = -1;
                        }
                    }

                    echartPlan.getData().add(continueErrorCount);
                }else {
                    echartPlan.getData().add(0);
                }
            }

        }

        return echartPlanList;
    }
}
